<script setup lang="ts">
import type { Post } from '#/api/system/post/model';

import { defineEmits, ref } from 'vue';

import { useVbenDrawer, useVbenForm } from '@vben/common-ui';

import { addPost, detailPost, updatePost } from '#/api/system/post/post';

import { drawerFormSchema } from './config-data';

const emit = defineEmits<{ reload: [] }>();

const [Form, formApi] = useVbenForm({
  showDefaultActions: false,
  schema: drawerFormSchema(),
});
const isUpdateRef = ref<boolean>(false);
const [Drawer, drawerApi] = useVbenDrawer({
  async onOpenChange(isOpen) {
    if (!isOpen) {
      return;
    }
    try {
      drawerApi.drawerLoading(true);
      const { postId, isUpdate } = drawerApi.getData();
      isUpdateRef.value = isUpdate;
      if (isUpdate) {
        const postData = await detailPost(postId);
        await formApi.setValues(postData);
      }
    } catch (error) {
      console.error(error);
    } finally {
      drawerApi.drawerLoading(false);
    }
  },
  onClosed() {
    formApi.resetForm();
  },
  async onConfirm() {
    try {
      this.confirmLoading = true;
      const { valid } = await formApi.validate();
      if (!valid) {
        return;
      }
      const data = await formApi.getValues<Post>();
      isUpdateRef.value ? await updatePost(data) : await addPost(data);
      emit('reload');
      drawerApi.close();
    } catch (error) {
      console.error(error);
    } finally {
      this.confirmLoading = false;
    }
  },
});
</script>

<template>
  <Drawer :title="isUpdateRef ? '编辑' : '新增'">
    <Form />
  </Drawer>
</template>
<style scoped lang="scss">
:deep(.el-input-number) {
  width: 100%;
}
</style>
